#-*- encoding: utf-8 -*-

import bitpimlite.vcard 

class VCards(bitpimlite.vcard.VCards):
  def next(self):
    # find vcard start
    field=value=None
    for field,value in self.vfile:
        if (field,value)!=(["BEGIN"], "VCARD"):
            continue
        found=True
        break
    if (field,value)!=(["BEGIN"], "VCARD"):
        # hit eof without any BEGIN:vcard
        raise StopIteration()
    # suck up lines
    lines=[]
    for field,value in self.vfile:
        if (field,value)!=(["END"], "VCARD"):
            lines.append( (field,value) )
            continue
        break
    if (field,value)!=(["END"], "VCARD"):
        raise VFileException("There is a BEGIN:VCARD but no END:VCARD")
    return VCard(lines)

IM_X_list = (u'X-MSN', u'X-ICQ', u'X-AIM', u'X-JABBER', u'X-GTALK', u'X-YAHOO',
             u'X-GROUPWISE', u'X-GADUGADU') # Evolution

IM_MESSAGING_list = (u'X-messaging/icq-All', u'X-messaging/xmpp-All', u'X-messaging/msn-All',
  u'X-messaging/gadu-All') # KDE


class VCard(bitpimlite.vcard.VCard):

  def getfield(self, field):
    try:
      ret = [ self._data[field], ]
    except KeyError:
      return []
    i = 2
    while True:
      try:
        ret.append(self._data['%s%s' % (field, i)])
      except KeyError:
        break
      i+=1
    return ret

  def _default_field(self, field, value, result):
    ff=field[0].upper().split(".")
    f0=ff[0]
    f1=ff[1] if len(ff)>1 else ''


    if 'X-MESSAGING' in field[0].upper() or f0 in IM_X_list or f1 in IM_X_list:
      return self._field_IM(field, value, result)
    else:
      return bitpimlite.vcard.VCard._default_field(self, field, value, result)
    
  def _field_IM(self, field, value, result):
    print field, value
    ff=field[0].upper().split(".")
    f0=ff[0]
    f1=ff[1] if len(ff)>1 else ''

    munge = {'XMPP' : 'JABBER'}

    if 'X-MESSAGING' in f0:
      protocol = f0[len('X-MESSAGING/'):].split('-')[0]
      protocol = munge.get(protocol, protocol) # Translate to 'standard' identifiers
      value = value.replace(u'\xee\x84\xa0', u'@') # KDE separates nick and network ...
    elif 'X-MESSAGING' in f1:
      protocol = f1[len('X-MESSAGING/'):].split('-')[0]
      protocol = munge.get(protocol, protocol)
      value = value.replace(u'\xee\x84\xa0', u'@') # ... with a nul byte
    elif f0 in IM_X_list:
      protocol = f0[len('X-'):]
    elif f1 in IM_X_list:
      protocol = f1[len('X-'):]

    value=self.unquote(value)
    # work out the types
    types=[]
    for f in field[1:]:
      if f.startswith("TYPE="):
        ff=f[len("TYPE="):].split(",")
      else: ff=[f]
      types.extend(ff)

    _type="other"
    for t in types:
      if t=="HOME": _type="home"
      if t=="WORK": _type="business"

    preferred="PREF" in types

    im={'address': value, 'type': _type, 'protocol': protocol}
    self._setvalue(result, "im", im, preferred)



if __name__ == '__main__':
  import sys
  f = bitpimlite.vcard.VFile(file(sys.argv[1]))
  print [x for x in VCards(f)]
  print x.getfield('phone')
  print x.getfield('name')
  print x.getfield('im')
      